package com.yyge.web.servlet;

import cn.hutool.crypto.digest.BCrypt;
import com.yyge.dao.Impl.UserInfoDaoImpl;
import com.yyge.entity.BaseEntity;
import com.yyge.entity.Userinfo;
import com.yyge.util.ServletUtil;
import com.yyge.vo.R;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 用户注册的API
 */

@WebServlet("/login/")
public class UserinfoLogin extends HttpServlet {


    /**
     * 用户注册POST
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BaseEntity baseEntity = ServletUtil.fetchDataFromRequest(req,Userinfo.class);
        Map<String, Object> params = baseEntity.getParams();
        Userinfo targrt = (Userinfo) baseEntity;

        UserInfoDaoImpl impl=new UserInfoDaoImpl();
        Map<String, Object> att = targrt.getParams();

        R r=new R();
        if(targrt.getName() == null){
            r=R.fail("用户名不能为空!");
            ServletUtil.writeResult2Client(resp,r);
            return;
        }

        if(targrt.getPhone() == null){
            r=R.fail("手机号不能为空!");
            ServletUtil.writeResult2Client(resp,r);
            return;
        }

        //判断两次输入密码是否一致
        String orPassword=att.get("repassword").toString().trim();
        String rePassword=targrt.getPassword()+"".trim();
        if(!(orPassword.equals(rePassword))){
            r=R.fail("两次输入密码不一致!");
            ServletUtil.writeResult2Client(resp,r);
            return;
        }

        //判断密码复杂程度
        System.out.println();
        if(targrt.getPassword().length() <= 6){
            r=R.fail("密码长度至少大于6位数!");
            ServletUtil.writeResult2Client(resp,r);
            return;
        }

        //默认男性
        if(targrt.getSex() == null){targrt.setSex(1);}

        //默认18岁
        if(targrt.getAge() == null){targrt.setAge(18);}
        /**
         * 如果通过了上面的验证则注册
         * 1.加密密码
         */
         String password = BCrypt.hashpw(targrt.getPassword());
         targrt.setPassword(password);
         /*新增用户*/
         impl.add(targrt);
         R ok = R.ok("注册成功");
         ServletUtil.writeResult2Client(resp,ok);
    }
}
